﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace Red.Launcher.ViewModels.Workspaces.Database.Sql
{
    public class Update : Query
    {
        #region Public Properties

        public override IEnumerable<SqlParameter> Parameters { get; }

        public string SetClause
        {
            get
            {
                IEnumerable< string > keys = Record.Metadata.Keys;

                string setClause = string.Join( ", ", keys.Select( ( key, index ) => ( $"{key} = {Parameters.ElementAt( index )}" ) ) );

                return setClause;
            }
        }

        public string Sql => $"UPDATE [{Settings.DatabaseName}].[dbo].[{Table}] SET {SetClause} WHERE id = '{Record.Id}'\n";

        #endregion Public Properties

        #region C-Tor
        
        public Update( Record record ) : base( record )
        {
            // ToList() will force immediate evaluation
            Parameters = ( from value in Record.Values select new SqlParameter( $"@updatevar{++ParameterIdPool}", value ?? DBNull.Value ) ).ToList();
        }

        #endregion C-Tor
    }
}
